var superagent = require('superagent');
var fs = require('fs');
var logTools = require('./logModel/logTools.js');

// 并发连接数的计数器
var concurrencyCount = 0;
var downloadNumber = 0;
var errorCount = 0;

function downloadImage(imageUrl, imageName, callback) {
    var imageUrl = "http://wpstatic.zuimeia.com/" + imageUrl;
    var imageLocalUrl = "./file/images/" + imageName;
    var superagentRequest = superagent.get(imageUrl).timeout(100000);

    logTools.log('当前并发数：' + (++concurrencyCount) + '当前下载第' + (++downloadNumber) + '个 *** ' + ' 正在抓取的是' + imageUrl);

    superagentRequest.pipe(fs.createWriteStream(imageLocalUrl));

    superagentRequest.on('end', function () {
        concurrencyCount--;
        logTools.logWithInfo(imageUrl + "图片下载完成" + "---错误个数：" + errorCount);
        callback(null, "当前图片下载完成");
    });

    superagentRequest.on("error", function (err, res) {
        errorCount++;
        logTools.logWithError(err + imageUrl + "图片下载失败");
    });
}

exports.downloadImage = downloadImage;